/*
 * DeleteNodesAction.java
 * 
 * Created by demory on Jul 13, 2008, 10:27:21 PM
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fpdev.apps.rtemaster.actions;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.fpdev.core.basenet.BLink;
import org.fpdev.core.basenet.BNode;
import org.fpdev.core.transit.Station;
import org.fpdev.apps.rtemaster.RouteMaster;

/**
 *
 * @author demory
 */
public class DeleteNodesAction implements ACAction {

  private Set<BNode> nodes_;
  
  private Map<Integer, Station> stations_;
  private Map<Integer, String> staNodeNames_;

  private DeleteLinksAction linksAction_;
  
  public DeleteNodesAction(Set<BNode> nodes) {
    nodes_ = nodes;
  }
  
  public boolean doAction(RouteMaster av) {
    
    // set of links incident to any of the deleted nodes
    Set<BLink> incLinks = new HashSet<BLink>();
      
    for (Iterator<BNode> nodes = nodes_.iterator(); nodes.hasNext();) {
      BNode node = nodes.next();
      
      // add all incident links for this node
      for (Iterator<BLink> links = av.getEngine().getBaseNet().incidentLinks(node).iterator(); links.hasNext();)
        incLinks.add(links.next());
      
      // remove the node from the basenet
      av.getEngine().getBaseNet().deleteNode(node);
      
      // back up station info
      if(node.isStation()) {
        stations_.put(node.getID(), node.getStation());
        staNodeNames_.put(node.getID(), node.getStation().getNodeName(node));
        node.getStation().removeNode(node);
      }
    }

    // remove the nodes from the db
    av.getEngine().getDB().deleteNodes(nodes_.iterator());
   
    // create and execute the delete links action
    if(!incLinks.isEmpty()) {
      linksAction_ = new DeleteLinksAction(incLinks);
      linksAction_.doAction(av);
    }
    
    return true;
  }

  public boolean undoAction(RouteMaster av) {
    throw new UnsupportedOperationException("Not supported yet.");
  }

  public String getName() {
    return "Delete Nodes";
  }
  
  
}
